<template>
  <div class="user-page art-full-height">
    <!-- 搜索栏 -->
    <Search v-model="searchForm" @search="handleSearch" @reset="resetSearchParams"></Search>

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格头部 -->
      <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
        <template #left>
          <ElSpace wrap style="margin-right: 5px">
            <ElButton v-auth="'common:upload:add'" @click="showDialog('add')" v-ripple
              >新增</ElButton
            >
          </ElSpace>
          <ElSpace wrap>
            <ElButton v-auth="'common:upload:del'" @click="deleteUser()" v-ripple
              >批量删除</ElButton
            >
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
      </ArtTable>

      <!-- 用户弹窗 -->
      <Dialog
        v-model:visible="dialogVisible"
        :type="dialogType"
        :user-data="currentUserData"
        @submit="handleDialogSubmit"
      />
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import { useTable } from '@/composables/useTable'
  import { fetchResourceTypes, deleteResourceApi } from '@/api/common'
  import Search from './modules/search.vue'
  import Dialog from './modules/dialog.vue'
  import { ElMessageBox, ElTooltip } from 'element-plus'
  import { useAuth } from '@/composables/useAuth'
  const { hasAuth } = useAuth()
  defineOptions({ name: 'User' })

  type UserListItem = Api.SystemManage.UserListItem

  // 弹窗相关
  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const currentUserData = ref<Partial<any>>({})

  // 选中行
  const selectedRows = ref<any[]>([])

  // 搜索表单
  const searchForm = ref({
    search: undefined,
    status: '',
    created_at: undefined
  })

  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    // 核心配置
    core: {
      apiFn: fetchResourceTypes,
      apiParams: {
        current: 1,
        size: 20,
        ...searchForm.value
      },
      // 自定义分页字段映射，未设置时将使用全局配置 tableConfig.ts 中的 paginationKey
      // paginationKey: {
      //   current: 'pageNum',
      //   size: 'pageSize'
      // },
      columnsFactory: () => [
        { type: 'selection' }, // 勾选列
        { type: 'index', width: 60, label: '序号' }, // 序号
        {
          prop: 'name',
          label: '类型名称',
          width: 280
        },
        {
          prop: 'created_at',
          label: '创建日期',
          sortable: true
          // checked: false, // 隐藏列
        },
        {
          prop: 'updated_at',
          label: '更新时间',
          sortable: true
        },
        {
          prop: 'operation',
          label: '操作',
          width: 140,
          fixed: 'right', // 固定列
          formatter: (row) => {
            return h('div', { style: 'text-align: right' }, [
              hasAuth('common:upload:edit') &&
                h(
                  ElTooltip,
                  { content: '编辑', placement: 'top' },
                  {
                    default: () =>
                      h(ArtButtonTable, {
                        type: 'edit',
                        onClick: () => showDialog('edit', row)
                      })
                  }
                ),
              hasAuth('common:upload:del') &&
                h(
                  ElTooltip,
                  { content: '删除', placement: 'top' },
                  {
                    default: () =>
                      h(ArtButtonTable, {
                        type: 'delete',
                        onClick: () => deleteUser(row)
                      })
                  }
                )
            ])
          }
        }
      ]
    }
  })

  /**
   * 搜索处理
   * @param params 参数
   */
  const handleSearch = (params: Record<string, any>) => {
    console.log(params)
    // 搜索参数赋值
    Object.assign(searchParams, params)
    getData()
  }

  /**
   * 显示用户弹窗
   */
  const showDialog = (type: 'add' | 'edit', row?: any): void => {
    console.log('打开弹窗:', { type, row })
    dialogType.value = type
    currentUserData.value = row || {}
    nextTick(() => {
      dialogVisible.value = true
    })
  }

  /**
   * 批量删除用户
   */
  const deleteUser = (row?: any) => {
    // 单个删除
    if (row) {
      ElMessageBox.confirm(`确定要删除【${row.name}】吗？`, '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        await deleteResourceApi([row.id])
        ElMessage.success('删除成功')
        getData()
      })
      return
    }

    // 批量删除
    if (!selectedRows.value.length) {
      ElMessage.warning('请先勾选要删除的用户')
      return
    }
    ElMessageBox.confirm(`确定要删除选中的${selectedRows.value.length}个用户吗？`, '批量删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
      const ids = selectedRows.value.map((item) => item.id)
      await deleteResourceApi(ids)
      ElMessage.success('批量删除成功')
      getData()
    })
  }

  /**
   * 处理弹窗提交事件
   */
  const handleDialogSubmit = async () => {
    try {
      dialogVisible.value = false
      currentUserData.value = {}
      getData() // 关键：弹窗提交后刷新用户列表
    } catch (error) {
      console.error('提交失败:', error)
    }
  }

  /**
   * 处理表格行选择变化
   */
  const handleSelectionChange = (selection: UserListItem[]): void => {
    selectedRows.value = selection
    console.log('选中行数据:', selectedRows.value)
  }
</script>

<style lang="scss" scoped>
  .user-page {
    :deep(.user) {
      .avatar {
        width: 40px;
        height: 40px;
        margin-left: 0;
        border-radius: 6px;
      }

      > div {
        margin-left: 10px;

        .user-name {
          font-weight: 500;
          color: var(--art-text-gray-800);
        }
      }
    }
  }
</style>
